<template>
  <div class="news-review">
    <n-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ t('menu.newsReview') }}</span>
          <n-button size="small" quaternary @click="resetColumnWidths">
            <template #icon>
              <n-icon><Icons name="refresh-outline" /></n-icon>
            </template>
            重置列宽
          </n-button>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-input
              v-model:value="searchForm.title"
              :placeholder="t('news.title')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-input
              v-model:value="searchForm.author"
              :placeholder="t('news.author')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1400"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" title="新闻详情" style="width: 80%">
      <div class="news-detail" v-if="currentNews">
        <div class="detail-item">
          <label>标题:</label>
          <span>{{ currentNews.title }}</span>
        </div>
        <div class="detail-item">
          <label>创作者:</label>
          <span>{{ currentNews.creator_name }}</span>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <span>{{ currentNews.status === 0 ? '待审核' : '已审核' }}</span>
        </div>
        <div class="detail-item">
          <label>创建时间:</label>
          <span>{{ new Date(currentNews.created_at).toLocaleString('zh-CN') }}</span>
        </div>
        <div class="detail-item">
          <label>内容:</label>
          <div class="content-html" v-html="currentNews.content"></div>
        </div>
        <div class="review-actions" v-if="currentNews.status === 0">
          <n-space>
            <n-button type="success" @click="handleApprove(currentNews)">
              通过审核
            </n-button>
            <n-button type="error" @click="handleReject(currentNews)">
              拒绝审核
            </n-button>
          </n-space>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NDataTable,
  NTag,
  NModal,
  NSpace,
  useMessage,
  useDialog
} from 'naive-ui'
import { EyeOutline, CheckmarkCircleOutline, CloseCircleOutline } from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import { newsApi } from '@/api'
import type { NewsItem } from '@/api'

const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const showModal = ref(false)
const currentNews = ref<any>(null)

const searchForm = reactive({
  title: '',
  author: ''
})

const tableData = ref<NewsItem[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => t('common.total', { count: itemCount })
})

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 50,
    maxWidth: 100
  },
  {
    title: t('news.title'),
    key: 'title',
    width: 200,
    minWidth: 150,
    maxWidth: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: '创作者',
    key: 'creator_name',
    width: 120,
    minWidth: 100,
    maxWidth: 180
  },
  {
    title: t('common.status'),
    key: 'status',
    width: 100,
    minWidth: 80,
    maxWidth: 120,
    render: (row: any) => {
      const statusText = row.status === 0 ? '待审核' : '已审核'
      return h(NTag, { 
        type: row.status === 0 ? 'warning' : 'success',
        size: 'small' 
      }, () => statusText)
    }
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 160,
    minWidth: 120,
    maxWidth: 200,
    render: (row: any) => {
      return new Date(row.created_at).toLocaleString('zh-CN')
    }
  },
  {
    title: t('common.operation'),
    key: 'actions',
    width: 240,
    minWidth: 200,
    maxWidth: 300,
    resizable: false,
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          onClick: () => handleView(row)
        }, { default: () => t('common.view'), icon: () => h(NIcon, () => h(EyeOutline)) }),
        
        h(NButton, {
          size: 'small',
          type: 'success',
          onClick: () => handleApprove(row),
          style: { marginLeft: '8px' },
          disabled: row.status !== 0
        }, { default: () => '通过', icon: () => h(NIcon, () => h(CheckmarkCircleOutline)) }),
        
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => handleReject(row),
          style: { marginLeft: '8px' },
          disabled: row.status !== 0
        }, { default: () => '拒绝', icon: () => h(NIcon, () => h(CloseCircleOutline)) })
      ]
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'news-review',
  defaultWidths: {
    'id': 60,
    'title': 200,
    'author': 120,
    'category': 100,
    'status': 100,
    'createTime': 160,
    'actions': 240
  }
})

const columns = computed(() => resizableColumns.value)

const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page - 1, // API页码从0开始，前端从1开始
      rows: pagination.pageSize,
      ...searchForm
    }
    
    const response = await newsApi.getPendingList(params)
    
    if (response.code === 200 && response.status === 'success' && response.data) {
      tableData.value = response.data.news_list || []
      pagination.itemCount = response.data.total || 0
    } else {
      message.error('加载数据失败')
    }
  } catch (error: any) {
    console.error('加载待审核数据错误:', error)
    if (error.status !== 401) {
      message.error(error.error || '加载数据失败')
    }
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.title = ''
  searchForm.author = ''
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleView = (row: any) => {
  currentNews.value = row
  showModal.value = true
}

const handleApprove = (row: any) => {
  dialog.info({
    title: '确认操作',
    content: `确认通过新闻"${row.title}"的审核吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        const response = await newsApi.review({
          news_id: row.id,
          status: 1,
          review_reason: ''
        })
        
        if (response.code === 200 && response.status === 'success') {
          message.success(response.message || '审核通过')
          showModal.value = false
          loadData()
        } else {
          message.error('审核失败')
        }
      } catch (error: any) {
        console.error('审核通过错误:', error)
        if (error.status !== 401) {
          message.error(error.error || '操作失败')
        }
      }
    }
  })
}

const handleReject = (row: any) => {
  // 创建一个输入框让用户输入拒绝理由
  const rejectReason = ref('')
  
  dialog.warning({
    title: '拒绝审核',
    content: () => h('div', [
      h('p', `确认拒绝新闻"${row.title}"的审核吗？`),
      h('p', { style: 'margin: 16px 0 8px 0; font-weight: bold;' }, '请输入拒绝理由：'),
      h('textarea', {
        value: rejectReason.value,
        onInput: (e: any) => rejectReason.value = e.target.value,
        placeholder: '请输入拒绝理由...',
        style: 'width: 100%; height: 80px; padding: 8px; border: 1px solid #d9d9d9; border-radius: 4px; resize: vertical;'
      })
    ]),
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      if (!rejectReason.value.trim()) {
        message.error('请输入拒绝理由')
        return false
      }
      
      try {
        const response = await newsApi.review({
          news_id: row.id,
          status: -1,
          review_reason: rejectReason.value.trim()
        })
        
        if (response.code === 200 && response.status === 'success') {
          message.success(response.message || '已拒绝审核')
          showModal.value = false
          loadData()
        } else {
          message.error('审核失败')
        }
      } catch (error: any) {
        console.error('审核拒绝错误:', error)
        if (error.status !== 401) {
          message.error(error.error || '操作失败')
        }
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.news-detail {
  padding: 16px;
}

.detail-item {
  margin-bottom: 16px;
}

.detail-item label {
  font-weight: bold;
  margin-right: 8px;
}

.content-html {
  border: 1px solid #e0e0e0;
  padding: 16px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.review-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
  text-align: center;
}
</style>
